import React, { useEffect, useState } from 'react';
import {
  Card,
  Avatar,
  Typography,
  Form,
  Input,
  Button,
  Upload,
  Spin,
  Divider,
  Modal
} from 'antd';
import {
  UserOutlined,
  MailOutlined,
  EditOutlined,
  UploadOutlined
} from '@ant-design/icons';
import { getCurrentUser, updateUser, uploadAvatar } from '../api/user';
import { updatePassword } from '../api/auth';

const { Title, Text } = Typography;

export default function Profile() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [signature, setSignature] = useState('');
  const [avatarUploading, setAvatarUploading] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);

  const [infoModal, setInfoModal] = useState({ open: false, title: '', content: '' });
  const [errorModal, setErrorModal] = useState({ open: false, title: '', content: '' });

  useEffect(() => {
    async function fetchUser() {
      setLoading(true);
      const res = await getCurrentUser();
      if (res.success) {
        setUser(res.user);
        setSignature(res.user.signature || '');
      } else {
        setErrorModal({
          open: true,
          title: '获取用户信息失败',
          content: res.message || '请稍后重试。',
        });
      }
      setLoading(false);
    }
    fetchUser();
  }, []);

  const handleSignatureChange = e => setSignature(e.target.value);

  const handleSave = async () => {
    setSaving(true);
    const res = await updateUser({ signature, avatar: user.avatar });
    if (res.success) {
      setUser(res.user);
      setInfoModal({
        open: true,
        title: '保存成功',
        content: '你的个人信息已成功更新。',
      });
    } else {
      setErrorModal({
        open: true,
        title: '保存失败',
        content: res.message || '请稍后重试。',
      });
    }
    setSaving(false);
  };

  if (loading) return <Spin style={{ marginTop: 100 }} />;

  if (!user) return null;

  return (
    <div style={{ maxWidth: 900, margin: '40px auto', padding: '0 16px' }}>
      <Card
        style={{
          width: '100%',
          borderRadius: 16,
          boxShadow: '0 4px 16px rgba(0,0,0,0.1)',
          padding: 32
        }}
      >
        {/* 用户信息头部 */}
        <div style={{ textAlign: 'center', marginBottom: 40 }}>
          <Upload
            name="avatar"
            showUploadList={false}
            customRequest={async ({ file, onSuccess, onError }) => {
              try {
                const res = await uploadAvatar(file);
                if (res.success) {
                  setUser(prev => ({ ...prev, avatar: `http://localhost:8080${res.url}` }));
                  localStorage.setItem('avatar', `http://localhost:8080${res.url}`);
                  onSuccess(res, file);
                } else {
                  onError(res.message);
                }
              } catch (e) {
                onError(e);
              }
            }}
            accept="image/*"
          >
            <div>
              <Avatar
                size={120}
                src={user.avatar ? user.avatar : undefined}
                icon={!user.avatar && <UserOutlined />}
                style={{ cursor: 'pointer', marginBottom: 12 }}
              />
              <br />
              <Button
                icon={<UploadOutlined />}
                loading={avatarUploading}
                size="middle"
              >
                更换头像
              </Button>
            </div>
          </Upload>
          <div style={{ marginTop: 24 }}>
            <Title level={3}>{user.name}</Title>
            <Text type="secondary">
              <MailOutlined style={{ marginRight: 6 }} />
              {user.email}
            </Text>
          </div>
        </div>

        <Divider orientation="left">基本信息</Divider>

        <Form layout="vertical" style={{ maxWidth: 600, margin: '0 auto' }}>
          <Form.Item label="个性签名">
            <Input.TextArea
              rows={3}
              value={signature}
              onChange={handleSignatureChange}
              placeholder="填写你的个性签名..."
              maxLength={100}
              showCount
              style={{ resize: 'none' }}
            />
          </Form.Item>
          <Form.Item>
            <div style={{ textAlign: 'center' }}>
              <Button
                type="primary"
                icon={<EditOutlined />}
                onClick={handleSave}
                loading={saving}
                size="large"
                style={{ padding: '0 40px' }}
              >
                保存修改
              </Button>
            </div>
          </Form.Item>
        </Form>

        <Divider orientation="left">安全设置</Divider>

        <Form layout="vertical" style={{ maxWidth: 600, margin: '0 auto' }}>
          <Form.Item>
            <Button 
              type="link" 
              onClick={() => setPasswordModalVisible(true)}
              style={{ paddingLeft: 0 }}
            >
              修改密码
            </Button>
          </Form.Item>
        </Form>

        <Modal
          title="修改密码"
          open={passwordModalVisible}
          onCancel={() => setPasswordModalVisible(false)}
          footer={null}
        >
          <Form
            layout="vertical"
            onFinish={async (values) => {
              const res = await updatePassword(values.oldPassword, values.newPassword);
              if (res.success) {
                setPasswordModalVisible(false);
                setInfoModal({
                  open: true,
                  title: '密码修改成功',
                  content: '你的密码已更新，下次请使用新密码登录。',
                });
              } else {
                setErrorModal({
                  open: true,
                  title: '密码修改失败',
                  content: res.message || '请检查输入信息或稍后重试。',
                });
              }
            }}
          >
            <Form.Item
              label="当前密码"
              name="oldPassword"
              rules={[{ required: true, message: '请输入当前密码!' }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item
              label="新密码"
              name="newPassword"
              rules={[
                { required: true, message: '请输入新密码!' },
                { min: 6, message: '密码至少6位!' }
              ]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item
              label="确认新密码"
              name="confirmNewPassword"
              dependencies={['newPassword']}
              rules={[
                { required: true, message: '请确认新密码!' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致!'));
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>

            <div style={{ textAlign: 'right' }}>
              <Button onClick={() => setPasswordModalVisible(false)} style={{ marginRight: 8 }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确认修改
              </Button>
            </div>
          </Form>
        </Modal>

        {/* 弹窗提示组件 */}
        <Modal
          open={infoModal.open}
          title={infoModal.title}
          onOk={() => setInfoModal({ ...infoModal, open: false })}
          onCancel={() => setInfoModal({ ...infoModal, open: false })}
        >
          <p>{infoModal.content}</p>
        </Modal>

        <Modal
          open={errorModal.open}
          title={errorModal.title}
          onOk={() => setErrorModal({ ...errorModal, open: false })}
          onCancel={() => setErrorModal({ ...errorModal, open: false })}
        >
          <p>{errorModal.content}</p>
        </Modal>
      </Card>
    </div>
  );
}
